package com.byxy.student.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.byxy.student.entity.UploadFile;
import com.byxy.student.service.UploadFileService;

@WebServlet("/servlet/file/downLoadFile")
public class StudentFileDownServlet extends HttpServlet {

	private UploadFileService fileService;

	@Override
	public void init() throws ServletException {
		super.init();
		if (null == fileService) {
			ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
			fileService = (UploadFileService) ctx.getBean(UploadFileService.class);
		}
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		int id = Integer.parseInt(req.getParameter("id"));
		UploadFile upLoadfile = fileService.findFileById(id);
		File file = new File(upLoadfile.getPath());
		if (file.exists()) {
			try {
				String realname = new String(upLoadfile.getName().getBytes("gbk"), "ISO-8859-1");
				resp.reset();
				resp.setCharacterEncoding("utf-8");
				// resp.setContentType("multipart/form-data");
				resp.setContentType("application/x-msdownload");
				resp.setHeader("Content-Disposition", "attachment;fileName=" + realname);
				InputStream inputStream = new FileInputStream(file);
				int fileLength = (int) file.length();
				resp.setContentLength(fileLength);
				OutputStream os = resp.getOutputStream();
				byte[] b = new byte[2048];
				int length;
				while ((length = inputStream.read(b)) > 0) {
					os.write(b, 0, length);
				}
				inputStream.close();
				os.close();
			} catch (UnsupportedEncodingException e1) {
				e1.printStackTrace();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
